package cn.ljy.mes.service.impl;

import cn.ljy.authority.service.impl.IBaseService;
import cn.ljy.common.exception.model.MyServiceException;
import cn.ljy.common.exception.model.MyWebException;
import cn.ljy.mes.dao.mapper.MesCarTechnologyMapper;
import cn.ljy.mes.model.MesCarModelConfig;
import cn.ljy.mes.model.query.MesCarModelConfigQuery;
import cn.ljy.mes.model.query.MesCarTechnologyQuery;
import cn.ljy.mes.service.MesCarModelConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;

@Service
public class IMesCarModelConfigService extends IBaseService<MesCarModelConfig, MesCarModelConfigQuery> implements MesCarModelConfigService {

    @Autowired
    private MesCarTechnologyMapper mesCarTechnologyMapper;

    @Override
    protected void enrichEntityFields(MesCarModelConfig carModelConfig){
        if(carModelConfig!=null){
            //工艺数量
            MesCarTechnologyQuery carTechnologyQuery=new MesCarTechnologyQuery();
            carTechnologyQuery.setCarModelConfig(carModelConfig);
            carModelConfig.setTechnologyNumber(mesCarTechnologyMapper.count(carTechnologyQuery));
        }
    }


    @Override
    protected void beforeSave(MesCarModelConfig carModelConfig) {
        if(carModelConfig.getCarModel().getId()==null){
            throw new MyWebException("验证失败：车型id能为空");
        }
    }

    @Override
    protected void beforeDelete(Serializable[] ids) {
        for(Serializable id:ids){
            //检查是否有车型调用本品牌
            //工艺数量
            MesCarTechnologyQuery carTechnologyQuery=new MesCarTechnologyQuery();
            carTechnologyQuery.setCarModelConfig(new MesCarModelConfig(id.toString()));
            int carTechnologyNumber=mesCarTechnologyMapper.count(carTechnologyQuery);
            if(carTechnologyNumber>0){
                MesCarModelConfig carModelConfig=mapper.findByIdNoRelation(id);
                throw new MyServiceException("删除失败："+carModelConfig.getName()+"下已经存在"+carTechnologyNumber+"个工艺，请先移除这些工艺再执行删除");
            }
        }
    }

}
